<template>
  <div class="profile-settings-container">
    <div class="page-header-wrapper">
      <el-button @click="goHome" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
    </div>
    <div class="settings-header">
      <h1 class="page-title">💖 个人设置</h1>
      <p class="page-subtitle">完善你的个人信息，让TA更了解你</p>
    </div>

    <!-- 头像区域 -->
    <div class="avatar-section card">
      <div class="avatar-wrapper">
        <el-avatar :size="120" :src="formData.avatar || defaultAvatar" class="user-avatar">
          <el-icon><User /></el-icon>
        </el-avatar>
        <div class="avatar-overlay" @click="handleAvatarClick">
          <el-icon><Camera /></el-icon>
          <span>更换头像</span>
        </div>
      </div>
      <input
        ref="avatarInput"
        type="file"
        accept="image/*"
        style="display: none"
        @change="handleAvatarChange"
      />
    </div>

    <!-- 个人信息表单 -->
    <div class="info-section card">
      <h2 class="section-title">📝 基本信息</h2>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px" label-position="left">
        
        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="formData.nickname"
            placeholder="请输入昵称"
            maxlength="20"
            show-word-limit
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 用户名（不可修改） -->
        <el-form-item label="用户名">
          <el-input v-model="formData.username" disabled>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">用户名不可修改</div>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="QQ邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入QQ邮箱"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">用于找回密码</div>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号（可选）"
            maxlength="11"
            clearable
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

      </el-form>
    </div>

    <!-- 密码修改 -->
    <div class="password-section card">
      <h2 class="section-title">🔐 修改密码</h2>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" label-position="left">
        
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码（6-20位）"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="warning" @click="handleChangePassword" :loading="passwordLoading">
            修改密码
          </el-button>
        </el-form-item>

      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" size="large" @click="handleSave" :loading="saveLoading">
        <el-icon><Check /></el-icon>
        保存修改
      </el-button>
    </div>

    <!-- 退出登录按钮（移动端显示在最下方） -->
    <div class="logout-section">
      <el-button type="danger" size="large" @click="handleLogout" plain class="logout-btn">
        <el-icon><SwitchButton /></el-icon>
        退出登录
      </el-button>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Camera, Lock, Message, Phone, Check, ArrowLeft, SwitchButton } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getUserInfo, uploadFile, updateUserInfo, changePassword } from '@/api'

const router = useRouter()
const userStore = useUserStore()

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 表单引用
const formRef = ref(null)
const passwordFormRef = ref(null)
const avatarInput = ref(null)

// 加载状态
const saveLoading = ref(false)
const passwordLoading = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为 2-20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { pattern: /@qq\.com$/, message: '请输入QQ邮箱', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为 6-20 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const res = await getUserInfo()
    if (res.code === 200 && res.data) {
      formData.username = res.data.username
      formData.nickname = res.data.nickname
      formData.email = res.data.email || ''
      formData.phone = res.data.phone || ''

      // 处理头像 URL
      let avatarUrl = res.data.avatar || ''
      if (avatarUrl && !avatarUrl.startsWith('http')) {
        // 如果是相对路径，拼接完整 URL
        const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
        avatarUrl = baseURL + avatarUrl
      }
      formData.avatar = avatarUrl

      console.log('加载的头像 URL:', formData.avatar)
    }
  } catch (error) {
    console.error('加载用户信息失败：', error)
    ElMessage.error('加载用户信息失败')
  }
}

// 点击头像
const handleAvatarClick = () => {
  avatarInput.value.click()
}

// 头像文件改变
const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 验证文件大小（最大 5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 5MB')
    return
  }

  try {
    const uploadFormData = new FormData()
    uploadFormData.append('file', file)

    const res = await uploadFile(uploadFormData)
    if (res.code === 200 && res.data) {
      // 后端返回的是相对路径，需要拼接完整 URL
      const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
      formData.avatar = baseURL + res.data

      console.log('头像上传成功，URL:', formData.avatar)
      ElMessage.success('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败：', error)
    ElMessage.error(error.response?.data?.msg || '头像上传失败')
  }
}

// 保存修改
const handleSave = async () => {
  // 表单验证
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  saveLoading.value = true
  try {
    // 处理头像 URL：保存到数据库时只保存相对路径
    let avatarPath = formData.avatar
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    if (avatarPath && avatarPath.startsWith(baseURL)) {
      // 去掉 baseURL，只保留相对路径
      avatarPath = avatarPath.replace(baseURL, '')
    }

    // 调用更新用户信息接口
    const res = await updateUserInfo({
      nickname: formData.nickname,
      email: formData.email,
      phone: formData.phone,
      avatar: avatarPath
    })

    if (res.code === 200) {
      ElMessage.success('保存成功')

      // 更新 store 中的用户信息
      userStore.setUserInfo(res.data)
    }
  } catch (error) {
    console.error('保存失败：', error)
    ElMessage.error(error.response?.data?.msg || '保存失败，请稍后重试')
  } finally {
    saveLoading.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  const valid = await passwordFormRef.value.validate().catch(() => false)
  if (!valid) return

  passwordLoading.value = true
  try {
    // 调用修改密码接口
    const res = await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    if (res.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')

      // 清空密码表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''

      // 退出登录
      setTimeout(() => {
        userStore.logout()
        router.push('/login')
      }, 1500)
    }
  } catch (error) {
    console.error('修改密码失败：', error)
    ElMessage.error(error.response?.data?.msg || '修改密码失败，请检查原密码是否正确')
  } finally {
    passwordLoading.value = false
  }
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 清除用户信息和 token
    userStore.logout()
    ElMessage.success('已退出登录')

    // 跳转到登录页
    router.push('/login')
  } catch {
    // 用户取消操作
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header-wrapper {
  margin-bottom: 10px;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.settings-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff69b4 0%, #ff85c0 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 10px;
}

.page-subtitle {
  color: #999;
  font-size: 14px;
}

.card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(255, 105, 180, 0.1);
  margin-bottom: 20px;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
}

.user-avatar {
  border: 4px solid #ffe0ec;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.2);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  font-size: 14px;
  gap: 5px;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

/* 信息区域 */
.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #ffe0ec;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.action-buttons .el-button {
  min-width: 200px;
  font-size: 16px;
  padding: 12px 40px;
}

/* 退出登录区域 */
.logout-section {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px dashed #ffe0ec;
}

.logout-btn {
  min-width: 200px;
  border-color: #ff6b6b;
  color: #ff6b6b;
}

.logout-btn:hover {
  background: #ff6b6b;
  border-color: #ff6b6b;
  color: white;
}

/* 响应式 */
@media (max-width: 768px) {
  .profile-settings-container {
    padding: 15px;
    padding-bottom: 30px;
  }

  .card {
    padding: 20px;
  }

  .avatar-section {
    padding: 30px;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }

  .action-buttons .el-button {
    width: 100%;
    min-width: auto;
  }

  /* 移动端退出登录按钮样式 */
  .logout-section {
    margin-top: 30px;
    padding-top: 20px;
    padding-bottom: 10px;
  }

  .logout-btn {
    width: 100%;
    min-width: auto;
  }
}
</style>

